package com.xiaokang.dao.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.xiaokang.dao.IFlightDao;
import com.xiaokang.pojo.Plane;
import com.xiaokang.utils.DBUtils;
import com.xiaokang.utils.DateUtils;

/**
 * 
 * @Description: 数据层
 * @author 小康
 * @version V1.0.0 2019年11月10日 上午8:00:53
 */
public class FlightDaoImpl implements IFlightDao {

	@Override
	public List<Plane> selectFlight() {
		List<Plane> planes = new ArrayList<Plane>(0);
		StringBuilder sql = new StringBuilder("select * from flight order by departureTime");
		ResultSet rs = null;
		try {
			rs = DBUtils.query(sql.toString());
			while (rs.next()) {
				Plane plane = new Plane(rs.getString("flightno"), rs.getString("departureCity"),
						rs.getString("arrivalCity"), DateUtils.parseStringToDate(rs.getString("departureTime")),
						DateUtils.parseStringToDate(rs.getString("arrivalTime")));
				planes.add(plane);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs);
		}
		return planes;
	}

	@Override
	public List<Plane> queryFlight(String departureCity, String arrivalCity) {
		List<Plane> planes = new ArrayList<Plane>(0);
		Object[] params = { departureCity, arrivalCity };
		StringBuilder sql = new StringBuilder(
				"select * from flight where departureCity=? and arrivalCity=? order by departureTime");
		ResultSet rs = null;
		try {
			rs = DBUtils.query(sql.toString(), params);
			while (rs.next()) {
				Plane plane = new Plane(rs.getString("flightno"), rs.getString("departureCity"),
						rs.getString("arrivalCity"), DateUtils.parseStringToDate(rs.getString("departureTime")),
						DateUtils.parseStringToDate(rs.getString("arrivalTime")));
				planes.add(plane);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs);
		}
		return planes;
	}

	@Override
	public int addFlight(Plane plane) {
		int affectRows = -1;
		StringBuilder sql = new StringBuilder("insert into flight values(?,?,?,?,?)");
		Object[] params = { plane.getFlightNo(), plane.getDepartureCity(), plane.getArrivalCity(),
				DateUtils.parseDateToString(plane.getDepartureTime()),
				DateUtils.parseDateToString(plane.getArrivalTime()) };
		try {
			affectRows = DBUtils.modify(sql.toString(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return affectRows;
	}

	@Override
	public int deleteFlight(String delFlightNo) {
		int affectRows = -1;
		StringBuilder sql = new StringBuilder("delete from flight where flightno=?");
		Object[] params = { delFlightNo };
		try {
			affectRows = DBUtils.modify(sql.toString(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return affectRows;
	}

	@Override
	public void exportToTxt(List<Plane> flights, String txtPath) {
		flights.forEach((perFlight) -> {
			String bookInfo = String.valueOf(perFlight.getFlightNo() + "  起飞城市：" + perFlight.getDepartureCity()
					+ "  起飞时间：" + DateUtils.parseDateToString(perFlight.getDepartureTime()) + "  到达城市："
					+ perFlight.getArrivalCity() + "  到达时间：" + DateUtils.parseDateToString(perFlight.getArrivalTime())
					+ "\n");
			File file = new File(txtPath);
			// 将对象信息bookInfo写入到文件内
			FileWriter fw = null;
			try {
				fw = new FileWriter(file, true);
				fw.write(bookInfo);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void saveToXML() {
		try {
			InputStream is = FlightDaoImpl.class.getClassLoader().getResourceAsStream("flights.xml");
			SAXReader reader = new SAXReader();
			Document document = reader.read(is);
			Element root = document.getRootElement();
			List<Element> flightsList = root.elements();

			// 先将所有flight元素清空
			for (Element perFlight : flightsList) {
				perFlight.getParent().remove(perFlight);
			}
			List<Plane> planes = selectFlight();
			// 将集合中的每个航班信息添加到xml中
			for (Plane perPlane : planes) {
				Element flightEle = root.addElement("flight");
				flightEle.addAttribute("flightNo", perPlane.getFlightNo());
				flightEle.addElement("departureCity").setText(perPlane.getDepartureCity());
				flightEle.addElement("departureTime").setText(DateUtils.parseDateToString(perPlane.getDepartureTime()));
				flightEle.addElement("arrivalCity").setText(perPlane.getArrivalCity());
				flightEle.addElement("arrivalTime").setText(DateUtils.parseDateToString(perPlane.getArrivalTime()));

			}
			// 保存到xml
			OutputFormat format = new OutputFormat();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(
					new FileOutputStream("D:\\jee_workspace\\FlightManagement\\src\\main\\resources\\flights.xml"),
					format);
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
